import mongoose from 'mongoose'
import xss from 'xss'
import R from 'ramda'
import multer from 'koa-multer'
import { get, post, put, del, required, controller } from '../decorator/route';
var schedule = require('node-schedule')

const Product = mongoose.model('Product')
const Yaoling = mongoose.model('Yaoling')
const Goto = mongoose.model('Goto')
const upload = multer({ dest: 'uploads/' }).single('file')

const scheduleCronstyle = async () => {
  schedule.scheduleJob('2 * * * * *', async () => {
    console.log('定时检测过期开启:' + new Date());
    let yaolings = await Yaoling.find({}).exec()
    yaolings.forEach(async (item, index) => {
      if (item.valid <= 0) {
        await Yaoling.findOne({_id: item._id}).remove()
      }
    })
  })
}

scheduleCronstyle();



@controller('/shop')
export class ProductController {
  @get('/products')
  async getProducts(ctx, next) {
    let { limit = 20 } = ctx.query
    let data = await Product.find({}).limit(Number(limit)).exec()
    
    ctx.body = {
      success: true,
      data
    }
  }

  @get('/product')
  @required({query: ['_id']})
  async getProduct(ctx, next) {
    let {_id} = ctx.query
    let data = await Product.findOne({
      _id: _id
    }).exec()
    
    ctx.body = {
      success: true,
      data
    }
  }

  @post('/add')
  async addProduct(ctx, next) {
    let product = ctx.request.body
    product = {
      title: xss(product.title),
      price: xss(product.price),
      intro: xss(product.intro),
      images: R.map(xss)(product.images),
      parameter: R.map(item => {
        return {
          key: xss(item.key),
          value: xss(item.value)
        }
      })(product.parameter)
    }

    let data
    try {
      data = new Product(product)
      await data.save()

      ctx.body = {
        success: true,
        data
      }
    } catch(e) {
      ctx.body = {
        success: false,
        error: e
      }
    }
  }


  @post('/update')
  async updateProduct(ctx, next) {
    let product = ctx.request.body
    let { _id } = product

    let data = await Product.findOne({
      _id
    }).exec()

    if (!data) return (ctx.body = { success: false, error: '没有该产品' })

    data.title = xss(product.title)
    data.price = xss(product.price)
    data.intro = xss(product.intro)
    data.images = R.map(xss)(product.images)
    data.parameter = R.map(item => {
      return {
        key: xss(item.key),
        value: xss(item.value)
      }
    })(product.parameter)

    try {
      data = await data.save()
      console.log(data)
      ctx.body = {
        success: true,
        data
      }
    } catch(e) {
      ctx.body = {
        success: false,
        error: e
      }
    }
  }

  @post('/del')
  async delProduct(ctx, next) {
    let { _id } = ctx.request.body

    let data = await Product.findOne({
      _id
    }).remove()

    ctx.body = {
      success: true
    }
  }

  @get('/addyaoling')
  async addyaoling(ctx, next) {
    ctx.res.setHeader("Access-Control-Allow-Origin", "*"); 
    let {
      gentime,
      latitude,
      lifetime,
      longtitude,
      sprite_id,
    } = ctx.query

    console.log(gentime)

    let yaoling = new Yaoling({
      gentime,
      latitude,
      lifetime,
      longtitude,
      sprite_id,
    })


    try {
      yaoling = await yaoling.save()
    } catch(e) {
      return (ctx.body = {
        success: false,
        error: '已有该妖灵!'
      })
    }
    
    console.log(yaoling.valid)

    ctx.body = {
      success: true,
      data: yaoling
    }
  }

  @get('/getyaolings')
  async getyaolings(ctx, next) {
    // let yaolings = await Yaoling.find({}).exec()
    let yaolings = await Yaoling.find({}, null, {sort: {valid: -1, request: 1}}).exec()

    // yaolings.forEach(async (item) => {
    //   if (!item.valid) {
    //     await Yaoling.find({_id: item._id}).remove()
    //   }
    // })

    // yaolings = await Yaoling.find({}).exec()
    
    ctx.body = {
      success: true,
      data: yaolings
    }
  }

  @get('/getyaoling')
  async getyaoling(ctx, next) {
    let yaolings = await Yaoling.find({}, null, {sort: {valid: -1, request: 1, latitude: 1, longtitude: 1}}).exec()

    let yaolingArr = []
    yaolings.forEach(async (item, index) => {
      if (item.valid <= 0) {
        await Yaoling.findOne({_id: item._id}).remove()
      } else {
        yaolingArr.push(item)
      }
    })

    let yaoling
    if (yaolingArr.length == 0) {
      return (ctx.body = '100')
    } else {
      yaoling = await Yaoling.findOne({_id: yaolingArr[0]._id}).exec()
      yaoling['request'] = 1
      yaoling = await yaoling.save()


      console.log(yaoling.point)
    }



    ctx.body = yaoling.point.length ? `${yaoling.point[0]},${yaoling.point[1]}` : ''
  }

  @get('/getnow')
  async getnow(ctx, next) {
    let gotonow = await Goto.findOne({_id: '5d91c49d0030b72494ea88d3'}).exec()
    console.log(gotonow)
    if(gotonow.isGo == 0 || !gotonow.point) {
      let yaolings = await Yaoling.find({}, null, {sort: {valid: -1, request: 1, latitude: 1, longtitude: 1}}).exec()

      let yaolingArr = []
      yaolings.forEach(async (item, index) => {
        if (item.valid <= 0) {
          await Yaoling.findOne({_id: item._id}).remove()
        } else {
          yaolingArr.push(item)
        }
      })

      let yaoling
      if (yaolingArr.length == 0) {
        return (ctx.body = '100')
      } else {
        yaoling = await Yaoling.findOne({_id: yaolingArr[0]._id}).exec()
        yaoling['request'] = 1
        yaoling = await yaoling.save()

      }
      let point = yaoling.point.length ? `${yaoling.point[0]},${yaoling.point[1]}` : ''
      gotonow.isGo = 1
      gotonow.point = point

      await gotonow.save()
      ctx.body = point
    } else {
      ctx.body = {
        success: true,
        data: gotonow
      }
    }
  }

  @get('/getnows')
  async getnows(ctx, next) {
    let gotonow = await Goto.find({}).exec()

    ctx.body = {
      success: true,
      data: gotonow
    }
  
  }

  @get('/rmyaoling')
  async rmyaoling(ctx, next) {
    await Yaoling.find({}).remove()
    ctx.body = {
      success: true
    }
  }

  @get('/test')
  async test(ctx, next) {
    let yaolings = await Yaoling.find({}, null, {sort: {valid: -1, request: 1, latitude: 1, longtitude: 1}}).exec()

    let yaolingArr = []
    yaolings.forEach(async (item, index) => {
      if (item.valid <= 0) {
        await Yaoling.findOne({_id: item._id}).remove()
      } else {
        yaolingArr.push(item)
      }
    })

    let yaoling
    if (yaolingArr.length == 0) {
      return (ctx.body = '100')
    } else {
      yaoling = await Yaoling.findOne({_id: yaolingArr[0]._id}).exec()
      yaoling['request'] = 1
      yaoling = await yaoling.save()


      console.log(yaoling.point)
    }



    ctx.body = yaoling.point.length ? `${yaoling.point[0]},${yaoling.point[1]}` : ''
  }


  @post('/posttest')
  async posttest(ctx, next) {
    let body = ctx.request.body
    let { key } = body
    console.log(key)
    ctx.body = 'xixi'
  }
}